package com.example.sms;

import java.util.LinkedHashMap;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ListView;


public class MainActivity extends Activity {
	
	public String phone_num;
	public static String[] hashMap;
	
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView list = (ListView) findViewById(R.id.sms_list);
        //ArrayList<String> msgList = getSMS();
        list.setAdapter(new Sms_list_adapter(getSMS(hashMap)));
    }
	
    public LinkedHashMap getSMS(String[] args) {
    	LinkedHashMap hashMap = new LinkedHashMap();
    	//ArrayList<String> sms = new ArrayList<String>();
        //fetch all inbox sms
        Cursor inboxCursor = getContentResolver().query(Uri.parse("content://mms-sms/conversations/"), null, null, null, null);
        inboxCursor.moveToFirst();
      //Create Hash Map of Field Definitions
        
		for (int i=0;i<inboxCursor.getCount();i++){
			//Store data
			Contact_map contact = new Contact_map(); 
                //get phone-number of sms
				String address = inboxCursor.getString(inboxCursor.getColumnIndex("address"));
				String body = inboxCursor.getString(inboxCursor.getColumnIndex("body"));
				contact.setMsg_body(body);
                //time stamp
                //Long time = (long) (inboxCursor.getColumnIndex("date"));
                //SimpleDateFormat date1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                
                //fetch contacts with same phone-number
                Cursor contactCursor=getContentResolver().query
                		(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.NUMBER+"='"+address+"'",null,null);
                if(contactCursor.getCount()>0)
                {
                	contactCursor.moveToFirst();
                    String name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
                    phone_num = name;
                    contact.setContactphone(name);
                    //sms.add(body+phone_num);                    
                }
                else 
                {  
                    // for unknown contact
                    //add number,name,message to list
                	phone_num = address;
                	contact.setContactphone(address);
                	//sms.add(body+phone_num);
                }
                contact.setContactNumber(i);
                hashMap.put(i, contact);
                inboxCursor.moveToNext();
            }
        //return sms;
		return hashMap;
        }
}
